package cn.hengzhu.main_manager.web.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.hengzhu.main_manager.repository.dao.ManageCompMapper;
import cn.hengzhu.main_manager.repository.dao.ManagePermissionMapper;
import cn.hengzhu.main_manager.repository.dao.ManageRolesMapper;
import cn.hengzhu.main_manager.repository.dao.ManageUserMapper;
import cn.hengzhu.main_manager.repository.domain.ManageComp;
import cn.hengzhu.main_manager.repository.domain.ManageCompExample;
import cn.hengzhu.main_manager.repository.domain.ManagePermission;
import cn.hengzhu.main_manager.repository.domain.ManagePermissionExample;
import cn.hengzhu.main_manager.repository.domain.ManageRoles;
import cn.hengzhu.main_manager.repository.domain.ManageRolesExample;
import cn.hengzhu.main_manager.repository.domain.ManageUser;
import cn.hengzhu.main_manager.repository.param.AddManagerParam;
import cn.hengzhu.main_manager.repository.param.ManagerListParam;
import cn.hengzhu.main_manager.repository.param.UpdateUserLoginParam;
import cn.hengzhu.main_manager.repository.vo.ManagerListVO;
import cn.hengzhu.main_manager.repository.vo.RoleVO;
import cn.hengzhu.main_manager.service.ManageCaseBoxService;
import cn.hengzhu.main_manager.utils.AjaxResult;
import cn.hengzhu.main_manager.utils.LayUiResultJson;
import cn.hengzhu.main_manager.utils.Md5Util;
import cn.hengzhu.main_manager.utils.UserContext;
import cn.hengzhu.main_manager.utils.ann.SystemControllerLog;
import cn.hengzhu.main_manager.utils.config.gzh.WeiXinConst;
import io.swagger.annotations.ApiParam;

@Controller
@RequestMapping("/main")
public class ManagerController {

	@Autowired
	private ManageUserMapper manageUserMapper;
	@Autowired
	private ManageRolesMapper manageRolesMapper;
	@Autowired
	private ManageCompMapper manageCompMapper;
	@Autowired
	private ManagePermissionMapper managePermissionMapper;
	@Autowired
	private ManageCaseBoxService manageCaseBoxService;

	/**
	 * 管理员列表
	 * 
	 * @param param
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getManagerList", method = RequestMethod.GET)
	public LayUiResultJson<ManagerListVO> getManagerList(ManagerListParam param) {
		List<ManagerListVO> list = new ArrayList<>();
		ManageUser user = UserContext.getUser();
		Integer compId = user.getCompId();
		Integer roleId = user.getRoleId();

		List<RoleVO> ownRoleList = new ArrayList<>();

		ManageRolesExample example = new ManageRolesExample();
		example.createCriteria().andCompIdEqualTo(compId);
		List<ManageRoles> roleList2 = manageRolesMapper.selectByExample(example);
		roleList2.stream().forEach(b -> {
			RoleVO roleVO = new RoleVO();
			roleVO.setName(b.getName());
			roleVO.setRoleId(b.getRoleId());
			if (b.getRoleId().equals(roleId)) {
				roleVO.setFlag((byte) 1);
			}
			ownRoleList.add(roleVO);
		});

		PageHelper.startPage(param.getPage(), param.getLimit(),true);
		List<ManageUser> managerList = manageUserMapper.getListByCompId(compId);
		PageInfo<ManageUser> pageInfo = new PageInfo<>(managerList);
		long count = pageInfo.getTotal();
		List<Integer> roleIdList = managerList.stream()
				.collect(Collectors.mapping(ManageUser::getRoleId, Collectors.toList())).stream().distinct()
				.collect(Collectors.toList());
		
		
		ManageRolesExample rolesExample=new ManageRolesExample();
		rolesExample.createCriteria().andRoleIdIn(roleIdList);
		List<ManageRoles> roleList = manageRolesMapper.selectByExample(rolesExample);
		
		Map<Integer, String> roleListMap = roleList.stream()
				.collect(Collectors.toMap(ManageRoles::getRoleId, ManageRoles::getName));
		List<Integer> compIds = managerList.stream()
				.collect(Collectors.mapping(ManageUser::getCompId, Collectors.toList())).stream().distinct()
				.collect(Collectors.toList());
		
		
		//		SELECT
//		<include refid="Base_Column_List" />
//		from manage_comp
//		WHERE COMP_ID in
//		<foreach collection="list" item="compId" open="(" close=")"
//			separator=",">
//			#{compId}
//		</foreach>
		ManageCompExample compExample=new ManageCompExample();
		compExample.createCriteria().andCompIdIn(compIds);
		List<ManageComp> compList = manageCompMapper.selectByExample(compExample);
		Map<Integer, ManageComp> CompByIdMap = compList.stream()
				.collect(Collectors.toMap(ManageComp::getCompId, a -> a));
		managerList.stream().forEach(a -> {
			ManagerListVO managerListVO = new ManagerListVO();
			managerListVO.setManagerId(a.getManagerId());
			managerListVO.setEmail(a.getEmail());
			managerListVO.setLoginName(a.getLoginName());
			managerListVO.setMobilePhone(a.getMobilePhone());
			managerListVO.setRealName(a.getRealName());
			managerListVO.setRoleId(a.getRoleId());
			managerListVO.setRoleName(roleListMap.get(a.getRoleId()));
			managerListVO.setFormUserName(a.getFormUserName());
			managerListVO.setRoleList(ownRoleList);
			Integer compId2 = a.getCompId();

			if (compId2 == 0) {
				managerListVO.setCompName("恒铸");
			} else {
				ManageComp manageComp = CompByIdMap.get(compId2);
				if (manageComp != null) {
					managerListVO.setCompName(manageComp.getCompName());
				} else {
					managerListVO.setCompName("该公司已被删除");

				}
			}
			list.add(managerListVO);
		});

		LayUiResultJson<ManagerListVO> result = new LayUiResultJson<>(count, list);
		return result;
	}

	/**
	 * 修改管理员账号信息
	 */
	@SystemControllerLog(description = "修改管理员账号信息")
	@ResponseBody
	@RequestMapping(value = "/updateUserLogin", method = RequestMethod.POST)
	public AjaxResult updateUserLogin(UpdateUserLoginParam param) {
		ManageUser user = UserContext.getUser();
		Integer ownRoleId = user.getRoleId();
		Integer roleId = param.getRoleId();
		ManageRoles otherRoles = manageRolesMapper.selectByPrimaryKey(roleId);
		String otherpermissions = otherRoles.getPermissions();
		ManageRoles ownRoles = manageRolesMapper.selectByPrimaryKey(ownRoleId);
		String ownpermissions = ownRoles.getPermissions();
		List<String> otherpermissionList = Arrays.asList(otherpermissions.split(","));
		List<String> ownpermissionList = Arrays.asList(ownpermissions.split(","));

		Integer managerId = param.getManagerId();
		// 查询被修改人的权限
		ManageUser manageUser = manageUserMapper.selectByPrimaryKey(managerId);
		Integer selectUserRoleId = manageUser.getRoleId();
		ManageRoles selectUserRoles = manageRolesMapper.selectByPrimaryKey(selectUserRoleId);
		List<String> selectUserpermissionList = Arrays.asList(selectUserRoles.getPermissions().split(","));
		if (user.getManagerId().equals(param.getManagerId()) && !roleId.equals(ownRoleId)) {
			return new AjaxResult("不可修改自己的权限");
		} else {
			if (ownpermissionList.containsAll(otherpermissionList)
					&& ownpermissionList.containsAll(selectUserpermissionList)) {
				String hash = Md5Util.hash("hengzhu123");
				param.setPassWord(hash);
			    List<Integer> codesInteger = otherpermissionList.stream().map(Integer::parseInt).collect(Collectors.toList());
				ManagePermissionExample permissionExample=new ManagePermissionExample();
				permissionExample.createCriteria().andIdIn(codesInteger);
				List<ManagePermission> permissionsByIds = managePermissionMapper.selectByExample(permissionExample);
				List<String> snList = permissionsByIds.stream()
						.collect(Collectors.mapping(ManagePermission::getSn, Collectors.toList()));
				try {
					if (snList.contains(WeiXinConst.PERMISSION_OPENBOX)) {
						manageUserMapper.updateInfoByManager(param);
					} else {
						manageCaseBoxService.clearBindByUpadateManager(param);
					}
					return new AjaxResult();
				} catch (Exception e) {
					return new AjaxResult("修改失败");
				}
			} else {
				return new AjaxResult("此账户权限高于您，不可修改");
			}
		}
	}

	/**
	 * @param param
	 *            添加管理人员账号
	 */
	@SystemControllerLog(description = "添加管理人员账号")
	@ResponseBody
	@RequestMapping(value = "/userAdd", method = RequestMethod.POST)
	public AjaxResult addUser(AddManagerParam param) {
		String loginName = param.getLoginName();
		ManageUser findByLoginName = manageUserMapper.findByLoginName(loginName);
		if (findByLoginName == null) {
			String hash = Md5Util.hash("hengzhu123");
			ManageUser record=new ManageUser();
			record.setCreateTime(new Date());
			record.setPassWord(hash);
			record.setLoginName(param.getLoginName());
			record.setRealName(param.getRealName());
			record.setMobilePhone(param.getMobilePhone());
			record.setEmail(param.getEmail());
			record.setCompId(param.getCompId());
			record.setRoleId(param.getRoleId());
			try {
				manageUserMapper.insertSelective(record);
				return new AjaxResult();
			} catch (Exception e) {
				return new AjaxResult("添加失败");
			}
		} else {
			return new AjaxResult("用户名已存在");
		}

	}

	/**
	 * @param param
	 *            删除员工
	 */
	@SystemControllerLog(description = "删除管理人员账号")
	@ResponseBody
	@RequestMapping(value = "/deleteUser", method = RequestMethod.GET)
	public AjaxResult deleteUser(@ApiParam(required = true, name = "managerId", value = "管理员Id") Integer managerId) {
		ManageUser user = UserContext.getUser();
		Integer ownManagerId = user.getManagerId();
		if (!ownManagerId.equals(managerId)) {
			try {
				manageUserMapper.deleteByPrimaryKey(managerId);
				return new AjaxResult();
			} catch (Exception e) {
				return new AjaxResult("删除失败");
			}
		} else {
			return new AjaxResult("删除失败,不能刪除自己");
		}

	}

	@RequestMapping("/checkName")
	@ResponseBody
	public Boolean checkName(String loginName) {
		ManageUser findByLoginName = manageUserMapper.findByLoginName(loginName);
		if (findByLoginName != null) {
			Map<String, String> map = new HashMap<>();
			map.put("msg", "用户名已存在");
			return false;
		} else {
			return true;
		}
	}

}
